#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
详细账户分析，包括所有可能的字段和计算值
"""

from futu import *
import time

def detailed_account_analysis():
    """详细分析所有账户的所有字段"""
    
    print("🔍 详细账户分析 - 寻找500美元或3917线索")
    print("="*80)
    
    brokers = [
        (SecurityFirm.FUTUSECURITIES, "富途证券 (FUTU HK)"),
        (SecurityFirm.FUTUINC, "Moomoo US"),
    ]
    
    markets = [
        (TrdMarket.US, "美股"),
        (TrdMarket.HK, "港股"),
    ]
    
    all_details = []
    
    for broker_firm, broker_name in brokers:
        print(f"\n🏢 详细分析券商: {broker_name}")
        print("-" * 60)
        
        for market, market_name in markets:
            print(f"\n📊 {broker_name} - {market_name}...")
            
            try:
                trd_ctx = OpenSecTradeContext(
                    filter_trdmarket=market,
                    host='127.0.0.1', 
                    port=11111, 
                    security_firm=broker_firm
                )
                
                ret, acc_data = trd_ctx.get_acc_list()
                
                if ret == RET_OK and len(acc_data) > 0:
                    print(f"✅ 找到 {len(acc_data)} 个账户")
                    
                    for index, account in acc_data.iterrows():
                        acc_id = account['acc_id']
                        
                        # 打印账户所有字段
                        print(f"\n📋 账户 {acc_id} 详细信息:")
                        for column in account.index:
                            print(f"   {column}: {account[column]}")
                        
                        # 检查是否包含3917
                        acc_id_str = str(acc_id)
                        if '3917' in acc_id_str:
                            print(f"   🎯 ★★★ 账户ID包含3917! ★★★")
                        
                        # 查询资金详细信息
                        print(f"\n💰 账户 {acc_id} 资金详细信息:")
                        
                        ret, fund_data = trd_ctx.accinfo_query(
                            trd_env=account['trd_env'],
                            acc_id=acc_id
                        )
                        
                        if ret == RET_OK and not fund_data.empty:
                            fund_info = fund_data.iloc[0]
                            
                            print("   📊 所有资金字段:")
                            for column in fund_info.index:
                                value = fund_info[column]
                                print(f"      {column}: {value}")
                                
                                # 检查是否有接近500的值
                                try:
                                    if isinstance(value, (int, float)) or (isinstance(value, str) and value.replace('.', '').replace('-', '').isdigit()):
                                        num_value = float(value)
                                        if abs(num_value - 500.0) < 50.0:
                                            print(f"         🎯 ★★★ 发现接近500的值: {column} = {num_value} ★★★")
                                except:
                                    pass
                        else:
                            print(f"   ❌ 资金查询失败")
                        
                        # 尝试查询持仓信息
                        print(f"\n📈 账户 {acc_id} 持仓信息:")
                        ret_pos, position_data = trd_ctx.position_list_query(
                            trd_env=account['trd_env'],
                            acc_id=acc_id
                        )
                        
                        if ret_pos == RET_OK and not position_data.empty:
                            print(f"   ✅ 找到 {len(position_data)} 个持仓")
                            for pos_index, position in position_data.iterrows():
                                print(f"   📋 持仓 {pos_index + 1}:")
                                for pos_column in position.index:
                                    pos_value = position[pos_column]
                                    print(f"      {pos_column}: {pos_value}")
                                    
                                    # 检查持仓值是否接近500
                                    try:
                                        if isinstance(pos_value, (int, float)) or (isinstance(pos_value, str) and pos_value.replace('.', '').replace('-', '').isdigit()):
                                            pos_num_value = float(pos_value)
                                            if abs(pos_num_value - 500.0) < 50.0:
                                                print(f"         🎯 ★★★ 持仓中发现接近500的值: {pos_column} = {pos_num_value} ★★★")
                                    except:
                                        pass
                        else:
                            print(f"   📭 无持仓或查询失败")
                        
                        print("-" * 40)
                        time.sleep(1)
                        
                else:
                    print(f"📭 无账户")
                    
            except Exception as e:
                print(f"❌ 查询异常: {e}")
                
            finally:
                trd_ctx.close()
                time.sleep(1)
    
    print(f"\n✅ 详细分析完成!")

if __name__ == "__main__":
    print("🎯 开始详细账户分析...")
    detailed_account_analysis()
